<template>
  <div>
    <el-row class="login-page">
      <el-col :span="12" class="bg"></el-col>
      <el-col :span="6" :offset="3" class="form">
        <!-- 注册表单 -->
        <el-form
          ref="form"
          size="large"
          autocomplete="off"
          v-if="isRegister"
          :model="registerData"
          :rules="rules"
        >
          <el-form-item>
            <h1>注册</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              v-model="registerData.password"
            />
          </el-form-item>
          <el-form-item prop="rePassword">
            <el-input
              :prefix-icon="Lock"
              type="password"
              placeholder="请再次输入密码"
              v-model="registerData.rePassword"
            />
          </el-form-item>
          <el-form-item prop="email">
            <el-input
              :prefix-icon="Message"
              placeholder="请输入邮箱"
              v-model="registerData.email"
            />
          </el-form-item>
          <el-form-item prop="role">
            <el-radio-group v-model="registerData.role">
                <el-radio :label="0">学生</el-radio>
                <el-radio :label="1">教师</el-radio>
            </el-radio-group>
          </el-form-item>
  
          <!-- 验证码输入框和按钮放同一行 -->
          <el-form-item prop="verificationCode">
            <el-row gutter="10">
              <el-col :span="16">
                <el-input
                  :prefix-icon="Message"
                  placeholder="请输入验证码"
                  v-model="registerData.verificationCode"
                />
              </el-col>
              <el-col :span="8">
                <el-button type="primary" @click="sendVerificationCode" style="width: 100%">
                  获取验证码
                </el-button>
              </el-col>
            </el-row>
          </el-form-item>
  
          <el-form-item>
            <el-button class="button" type="primary" auto-insert-space @click="register">
              注册
            </el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister = false; clearRegisterData()">
              ← 返回
            </el-link>
          </el-form-item>
        </el-form>
  
        <!-- 登录表单 -->
        <el-form
          ref="form"
          size="large"
          autocomplete="off"
          v-else
          :model="registerData"
          :rules="rules"
        >
          <el-form-item>
            <h1>登录</h1>
          </el-form-item>
          <el-form-item prop="username">
            <el-input :prefix-icon="User" placeholder="请输入用户名" v-model="registerData.username" />
          </el-form-item>
          <el-form-item prop="password">
            <el-input
              name="password"
              :prefix-icon="Lock"
              type="password"
              placeholder="请输入密码"
              v-model="registerData.password"
            />
          </el-form-item>
          <el-form-item class="flex">
            <div class="flex">
              <el-checkbox>记住我</el-checkbox>
              <el-link type="primary" :underline="false" @click="showForgotPasswordDialog = true">忘记密码？</el-link>
            </div>
          </el-form-item>
          <!-- 登录按钮 -->
          <el-form-item>
            <el-button class="button" type="primary" auto-insert-space @click="login">登录</el-button>
          </el-form-item>
          <el-form-item class="flex">
            <el-link type="info" :underline="false" @click="isRegister = true; clearRegisterData()">
              注册 →
            </el-link>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  
    <!-- 忘记密码对话框 -->
    <el-dialog v-model="showForgotPasswordDialog" title="忘记密码" width="30%">
      <el-form :model="forgotPasswordForm" :rules="forgotPasswordRules" ref="forgotPasswordFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="forgotPasswordForm.username" placeholder="请输入您的用户名"></el-input>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="forgotPasswordForm.email" placeholder="请输入您的邮箱"></el-input>
        </el-form-item>
        
        <el-form-item label="验证码" prop="verificationCode">
          <el-row gutter="10">
            <el-col :span="16">
              <el-input v-model="forgotPasswordForm.verificationCode" placeholder="请输入验证码"></el-input>
            </el-col>
            <el-col :span="8">
              <el-button type="primary" @click="sendResetVerificationCode" :disabled="forgotPasswordForm.email === ''" style="width: 100%">
                获取验证码
              </el-button>
            </el-col>
          </el-row>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="forgotPasswordForm.newPassword" type="password" show-password placeholder="请输入新密码"></el-input>
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="forgotPasswordForm.confirmPassword" type="password" show-password placeholder="请再次输入新密码"></el-input>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="showForgotPasswordDialog = false">取消</el-button>
          <el-button type="primary" @click="submitForgotPassword" :loading="forgotPasswordLoading">
            确认重置
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
import { User, Lock, Message } from '@element-plus/icons-vue'
import { ref, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { userRegisterService, userLoginService, sendVerificationCodeService, forgotPasswordService } from '@/api/user.js'
import { useTokenStore } from '@/stores/token.js'
import { useRouter } from 'vue-router'
import instance from '@/utils/request'

// 获取错误防抖函数
const showError = (message) => {
  // 这里我们不需要实现，只是通过引入request确保使用相同的错误显示机制
  ElMessage.error(message);
};

// 控制注册与登录表单的显示，默认显示登录
const isRegister = ref(false)

// 定义数据模型
const registerData = ref({
  username: '',
  password: '',
  rePassword: '',
  email: '',
  verificationCode: '',
  role: 0 // 默认为学生
})

// 校验密码的函数
const checkRePassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次确认密码'))
  } else if (value !== registerData.value.password) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

// 定义表单校验规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位字符', trigger: 'blur' }
  ],
  rePassword: [{ validator: checkRePassword, trigger: 'blur' }],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  verificationCode: [{ required: true, message: '请输入验证码', trigger: 'blur' }]
}

// 发送验证码
const sendVerificationCode = async () => {
  if (!registerData.value.email) {
    showError('请输入邮箱')
    return
  }
  try {
    let result = await sendVerificationCodeService({ email: registerData.value.email })
    ElMessage.success(result.msg ? result.msg : '验证码已发送，请查收')
  } catch (error) {
    // 错误由响应拦截器处理
    console.error('发送验证码错误:', error)
  }
}

// 注册函数
const register = async () => {
  try {
    let result = await userRegisterService(registerData.value)
    ElMessage.success(result.msg ? result.msg : '注册成功')
    isRegister.value = false // 注册成功后切换到登录界面
    clearRegisterData()
  } catch (error) {
    // 错误由响应拦截器处理
    console.error('注册错误:', error)
  }
}

// 登录
const tokenStore = useTokenStore()
const router = useRouter()

const login = async () => {
  try {
      // 检查表单输入
      if (!registerData.value.username) {
          showError('请输入用户名')
          return
      }
      if (!registerData.value.password) {
          showError('请输入密码')
          return
      }
      
      const response = await userLoginService(registerData.value)
      
      if (!response.success) {
          // 这里不显示错误，因为响应拦截器已经显示了
          return
      }
      
      // 解析 JWT token
      const token = response.data
      const tokenParts = token.split('.')
      if (tokenParts.length === 3) {
          const payload = JSON.parse(atob(tokenParts[1]))
          const role = payload.claims.role
          
          // 存储 token 和角色信息
          tokenStore.setToken(token)
          tokenStore.setUserRole(role)
          
          // 如果是教师且被转换为学生角色
          if (registerData.value.role === 1 && role === 0) {
              ElMessage.warning('您的教师身份正在审核中，暂时以学生身份登录')
          } else {
              ElMessage.success('登录成功')
          }
          
          router.push('/')
      } else {
          throw new Error('无效的 token 格式')
      }
  } catch (error) {
      console.error('登录错误:', error)
      // 这里不再显示错误信息，因为响应拦截器已经处理了
  }
}

// 清空表单数据
const clearRegisterData = () => {
  registerData.value = {
    username: '',
    password: '',
    rePassword: '',
    email: '',
    verificationCode: '',
    role: 0
  }
}

// 忘记密码相关
const showForgotPasswordDialog = ref(false)
const forgotPasswordFormRef = ref(null)
const forgotPasswordLoading = ref(false)

const forgotPasswordForm = ref({
  username: '',
  email: '',
  verificationCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 验证确认密码是否一致
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== forgotPasswordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const forgotPasswordRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入有效的邮箱地址', trigger: 'blur' }
  ],
  verificationCode: [
    { required: true, message: '请输入验证码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 5, max: 16, message: '长度为5~16位字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次确认密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 发送重置密码的验证码
const sendResetVerificationCode = async () => {
  if (!forgotPasswordForm.value.email) {
    showError('请输入邮箱')
    return
  }
  
  try {
    let result = await sendVerificationCodeService({ email: forgotPasswordForm.value.email })
    ElMessage.success(result.msg ? result.msg : '验证码已发送，请查收')
  } catch (error) {
    // 错误由响应拦截器处理
    console.error('发送验证码错误:', error)
  }
}

// 提交忘记密码表单
const submitForgotPassword = () => {
  forgotPasswordFormRef.value.validate(async (valid) => {
    if (valid) {
      forgotPasswordLoading.value = true
      try {
        const response = await forgotPasswordService({
          username: forgotPasswordForm.value.username,
          email: forgotPasswordForm.value.email,
          verificationCode: forgotPasswordForm.value.verificationCode,
          newPassword: forgotPasswordForm.value.newPassword,
          confirmPassword: forgotPasswordForm.value.confirmPassword
        })
        
        ElMessage.success('密码重置成功，请使用新密码登录')
        showForgotPasswordDialog.value = false
        
        // 清空表单
        forgotPasswordForm.value = {
          username: '',
          email: '',
          verificationCode: '',
          newPassword: '',
          confirmPassword: ''
        }
      } catch (error) {
        // 错误由响应拦截器处理
        console.error('重置密码错误:', error)
      } finally {
        forgotPasswordLoading.value = false
      }
    }
  })
}
</script>
  
<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url('@/assets/chahua.png') no-repeat 60% center / 240px auto,
      url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>
  